package cn.qj.ymcc.web.controller;

import cn.qj.ymcc.result.JSONResult;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.SignVersion;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/oss")
public class OSSController {
    @PostMapping("/uploadFile")    //名字不同加@RequestParam
    public JSONResult uploadFile(@RequestParam MultipartFile fileName) {
        // Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = ("sanqi-yumm");
        String region = "cn-hangzhou";

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = new OSSClientBuilder().build(endpoint,
                "LTAI5tRUsPdUHBgicK8MeWG5",
                "ZeD0ra2QuACugqySloEerhy6qS8wjY"
        );
        try {
            // 2. 上传文件
            //获取时间
            String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            //获取后缀
            String substring = fileName.getOriginalFilename().substring(fileName.getOriginalFilename().lastIndexOf("."));
            // 文件名
            String objectName = format + "/" + System.currentTimeMillis() + substring;
            ossClient.putObject(bucketName, objectName, fileName.getInputStream());
            System.out.println("文件 " + objectName + " 上传成功。");
            // https://sanqi-yumm.oss-cn-hangzhou.aliyuncs.com/2025/07/25/1753441887500.png
            return JSONResult.success("https://sanqi-yumm.oss-cn-hangzhou.aliyuncs.com/"+objectName);
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return JSONResult.error("文件上传失败");
    }
}
